package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.service.pay.WeiXinPayService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 岳剑飞
 * @Company http://www.ithiema.com
 */
@RestController
@RequestMapping("/wxpay")
public class PayController {

    @Reference
    private OrderService orderService;
    @Reference
    private WeiXinPayService weiXinPayService;

    /**
     * 创建支付
     *
     * @param orderId
     * @return
     */
    @GetMapping("/createNative")
    public Map createNative(String orderId) {
        // 获取当前 登录用户
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        // 根据订单id查询订单
        Order order = orderService.findById(orderId);

        if (order != null) {  //判断订单是否存在
            if ("0".equals(order.getPayStatus()) && "0".equals(order.getOrderStatus()) && username.equals(order.getUsername())) {
                //调用方法,生成微信支付二维码
                return weiXinPayService.createNative(orderId, order.getPayMoney(), "http://hero.easy.echosite.cn/wxpay/notify.do");
            } else {
                return null;
            }
        } else {

            return null;
        }

    }

    /**
     * 支付成功后,回调
     */
    @RequestMapping("/notify")
    public Map notifyLogic(HttpServletRequest request) throws IOException {
        System.out.println("支付成功回调开始。。。。");
        InputStream inputStream;
        try {
            inputStream = request.getInputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();
            inputStream.close();

            String result = new String(outputStream.toByteArray(), "utf-8");
            System.out.println(result);
            weiXinPayService.notifyLogic(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new HashMap();
    }
}
